import json
import math

from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

import logging
import copy

conquest_match_event_project_api = Blueprint('conquest_match_event_project_api', __name__)
conquest_match_event_project_down_api = Blueprint('conquest_match_event_project_down_api', __name__)
conquest_match_event_project_optimization_update_api = Blueprint('conquest_match_event_project_optimization_update_api', __name__)
conquest_match_event_project_group_num_update_api = Blueprint('conquest_match_event_project_group_num_update_api', __name__)



@conquest_match_event_project_api.route('/conquest_match_event_project', methods=['POST'])
def conquest_match_event_project():
    params = json.loads(request.data)
    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'detail':
        query = ConquestMatchEventProject.query.filter_by(project=_project).first()
        tmp = {
            "project": int(query.project),
            'basic': json.loads(query.basic),
            'reward': json.loads(query.reward),
            'task_desc': json.loads(query.task_desc)
        }
        result_data['data']['item'] = tmp
    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']
        if _part == 'basic':
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'basic': json.dumps(_data)
            })
        elif _part == 'server_point':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            reward["serverPointGold"] = _data['gold']
            reward["serverPointSilver"] = _data['silver']
            reward["serverPointBronze"] = _data['bronze']
            reward["battle_num"] = _data['battle_num']
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'global_server_rank':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            reward["globalServerRankReward"] = _data
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'global_personal_rank':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            reward["globalPersonalRank"]['show_size'] = _data['show_size']
            reward["globalPersonalRank"]['limit_score'] = _data['limit_score']
            reward["globalPersonalRank"]['reward'] = _data['reward']
            reward['token_id'] = _data['token_id']
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'sub_server_goal':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            reward["subServer"]['goalReward'] = _data
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'sub_server_rank':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            if _data['rank_index'] == 0:
                reward["subServer"]['rankRewardGroup'] = _data['reward']
            if _data['rank_index'] == 1:
                reward["subServer"]['rankRewardRingWin'] = _data['reward']
            if _data['rank_index'] == 2:
                reward["subServer"]['rankRewardRingLose'] = _data['reward']
            if _data['rank_index'] == 3:
                reward["subServer"]['rankRewardPeakWin'] = _data['reward']
            if _data['rank_index'] == 4:
                reward["subServer"]['rankRewardPeakLose'] = _data['reward']
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'empire_goal':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            t = _data['data_type']
            fieldMap = {
                'group': 'groupGoal',
                'ring': 'ringGoal',
                'peak': 'peakGoal'
            }
            reward["empire"][fieldMap[t]] = _data['data_reward']
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'empire_rank':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            fieldMap = {
                'group': 'groupRank',
                'ring': 'ringRank',
                'peak': 'peakRank'
            }
            if _data['type'] == 'group':
                reward["empire"]['show_size'] = _data['show_size']
                reward["empire"]['limit_score'] = _data['limit_score']
            reward["empire"][fieldMap[_data['type']]] = _data['reward']
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'satellite_goal':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            t = _data['data_type']
            fieldMap = {
                'group': 'groupGoal',
                'ring': 'ringGoal',
                'peak': 'peakGoal'
            }
            reward["satellite"][fieldMap[t]] = _data['data_reward']
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'satellite_rank':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            fieldMap = {
                'group': 'groupRank',
                'ring': 'ringRank',
                'peak': 'peakRank'
            }
            if _data['type'] == 'group':
                reward["satellite"]['show_size'] = _data['show_size']
                reward["satellite"]['limit_score'] = _data['limit_score']
            reward["satellite"][fieldMap[_data['type']]] = _data['reward']
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'brave_goal':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            reward["brave"]["goal"] = _data['data_reward']
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'brave_rank':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            reward["brave"]['show_size'] = _data['show_size']
            reward["brave"]['limit_score'] = _data['limit_score']
            reward["brave"]["rank"] = _data['reward']
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'task_desc':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            task_desc = json.loads(conquest_match_event_project_data.task_desc)
            task_desc['task_param_1'] = _data['task_param_1']
            task_desc['server_task_list'] = _data['server_task_list']
            task_desc['user_task_list'] = _data['user_task_list']
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'task_desc': json.dumps(task_desc)
            })
        elif _part == 'score_building':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            reward["score_building"] = _data
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'multi_basic':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            fieldMap = {
                'group': 'groupBasic',
                'ring': 'ringBasic',
                'peak': 'peakBasic'
            }
            reward[fieldMap[_data['type']]] = _data['data']
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'hospital_capacity':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            reward["hospital"]["switch"] = _data['switch']
            reward["hospital"]["capacity"] = _data['data_reward']
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'hospital_revive':
            conquest_match_event_project_data = ConquestMatchEventProject.query.filter_by(project=_project).first()
            reward = json.loads(conquest_match_event_project_data.reward)
            reward["hospital"]["revive_switch"] = _data['revive_switch']
            reward["hospital"]["revive"] = _data['data_reward']
            reward["hospital"]["troop_num_unit"] = _data['troop_num_unit']
            ConquestMatchEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    elif _action == 'score_list':
        with open(STATIC_PATH + 'conquest_match_event_project/task_list.json', encoding='UTF-8') as f:
            data = json.load(f)
            server_task_list = []
            user_task_list = []
            for i in data:
                if i['rank_type'] in [0, 2]:
                    server_task_list.append(copy.deepcopy(i))
                else:
                    user_task_list.append(copy.deepcopy(i))
            return json.dumps({
                'task_list': data,
                'server_task_list': server_task_list,
                'user_task_list': user_task_list
            })
    elif _action == 'get_doc_id_list':
        doc_id_list = get_doc_id_list('conquest_event', 'title')
        doc_id_list_filter = []
        for i in doc_id_list:
            if i['value'] % 10 == 0:
                doc_id_list_filter.append(copy.deepcopy(i))
        return json.dumps(doc_id_list_filter)
    elif _action == 'get_buff_id_list':
        buff_query = CommonBuff.query.order_by('id').all()
        buff_id_list = []
        buff_id_list.append({
            'value': -1,
            'label': f"-1 - 不投放"
        })
        for i in buff_query:
            buff_id_list.append({
                'value': i.id,
                'label': f"{i.id} - {i.name}"
            })
        return json.dumps(buff_id_list)
    elif _action == 'get_shop_type_list':
        with open(STATIC_PATH + 'shop_name.json', encoding='UTF-8') as f:
            data = json.load(f)
        shop_list = [
            {
                'value': -1,
                'label': f"{-1} - 不使用兑换商店"
            }
        ]
        for j in data:
            i = data[j]
            shop_list.append({
                'value': i['shop_id'],
                'label': f"{i['shop_id']} - {i['shop_name']}"
            })
        return json.dumps(shop_list)
    elif _action == 'check_before_public':
        _skip = params['skip']

        def genFailMessage(msg):
            return json.dumps({
                "status": "fail",
                "msg": msg
            })

        def get_goal_max_target(a, key):
            return a[len(a) - 1][key]

        try:
            if _project == -1:
                if _skip:
                    project_data = ConquestMatchEventProject.query.order_by('project').filter_by(publish=1).all()
                else:
                    project_data = ConquestMatchEventProject.query.order_by('project').all()
            else:
                if _skip:
                    project_data = ConquestMatchEventProject.query.filter_by(project=_project, publish=1).all()
                else:
                    project_data = ConquestMatchEventProject.query.filter_by(project=_project).all()
            for current_project in project_data:
                project = int(current_project.project)
                basic = json.loads(current_project.basic)
                reward = json.loads(current_project.reward)
                # 总服务器积分榜
                _max_server_rank = 0
                if len(reward['serverPointGold']) > 0:
                    _max_server_rank = max(_max_server_rank, reward['serverPointGold'][len(reward['serverPointGold']) - 1]['to'])
                    _gold_server_num = reward['serverPointGold'][len(reward['serverPointGold']) - 1]['to'] - reward['serverPointGold'][0]['from'] + 1
                else:
                    _gold_server_num = 0
                if len(reward['serverPointSilver']) > 0:
                    _max_server_rank = max(_max_server_rank, reward['serverPointSilver'][len(reward['serverPointSilver']) - 1]['to'])
                    _silver_server_num = reward['serverPointSilver'][len(reward['serverPointSilver']) - 1]['to'] - reward['serverPointSilver'][0]['from'] + 1
                else:
                    _silver_server_num = 0
                if len(reward['serverPointBronze']) > 0:
                    _max_server_rank = max(_max_server_rank, reward['serverPointBronze'][len(reward['serverPointBronze']) - 1]['to'])
                    _bronze_server_num = reward['serverPointBronze'][len(reward['serverPointBronze']) - 1]['to'] - reward['serverPointBronze'][0]['from'] + 1
                else:
                    _bronze_server_num = 0
                # if reward['globalServerRankReward'][len(reward['globalServerRankReward']) - 1]['to'] > _max_server_rank:
                #     return genFailMessage(
                #         f"[PID={project}] 总服务器积分排名奖励 服务器排名({reward['globalServerRankReward'][len(reward['globalServerRankReward']) - 1]['to']}) > 服务器积分配置-最大服务器数量({_max_server_rank})")
                # 小组赛rank
                # _group_max_server = math.ceil(max(_gold_server_num, _silver_server_num, _bronze_server_num) / reward['groupBasic']['group_num'])
                # if len(reward['subServer']['rankRewardGroup']) > _group_max_server:
                #     return genFailMessage(f"[PID={project}] 局内服务器相关配置-小组赛积分奖励 服务器排名({len(reward['subServer']['rankRewardGroup'])}) > 每个小组服务器上限({_group_max_server})")
                # # 擂台赛rank
                # _ring_max_server = math.ceil(_max_server_rank / reward['ringBasic']['ring_num'])
                # if len(reward['subServer']['rankRewardRingWin']) > _ring_max_server:
                #     return genFailMessage(f"[PID={project}] 局内服务器相关配置-擂台赛win奖励 服务器排名({len(reward['subServer']['rankRewardRingWin'])}) > 擂台赛最大服务器数({_ring_max_server})")
                # if len(reward['subServer']['rankRewardRingLose']) > _ring_max_server:
                #     return genFailMessage(f"[PID={project}] 局内服务器相关配置-擂台赛lose奖励 服务器排名({len(reward['subServer']['rankRewardRingLose'])}) > 擂台赛最大服务器数({_ring_max_server})")
                # # 巅峰擂台赛rank
                # if len(reward['subServer']['rankRewardPeakWin']) > reward['ringBasic']['ring_num']:
                #     return genFailMessage(f"[PID={project}] 局内服务器相关配置-巅峰擂台赛win奖励 服务器排名({len(reward['subServer']['rankRewardPeakWin'])}) > 巅峰擂台赛最大服务器数({basic['ring_num']})")
                # if len(reward['subServer']['rankRewardPeakLose']) > reward['ringBasic']['ring_num']:
                #     return genFailMessage(f"[PID={project}] 局内服务器相关配置-巅峰擂台赛lose奖励 服务器排名({len(reward['subServer']['rankRewardPeakLose'])}) > 巅峰擂台赛最大服务器数({basic['ring_num']})")

                # 活动医院的提前复活的数量上限必须小于等于医院容量
                if reward['hospital']['switch'] == 1 and reward['hospital']['revive_switch'] == 1:
                    if len(reward['hospital']['capacity']) <= 0 or len(reward['hospital']['revive']) <= 0:
                        return genFailMessage(
                            f"[PID={project}] 活动医院 意外错误：活动医院 / 提前复活 数据校验失败(01)")
                    max_capacity = get_goal_max_target(reward['hospital']['capacity'], 'capacity_to')
                    max_recive = get_goal_max_target(reward['hospital']['revive'], 'to')

                    capacity_sum = 0
                    for i in reward['hospital']['capacity']:
                        capacity_sum += i['capacity_to'] * i['percent']
                    capacity_sum = math.ceil(capacity_sum * 0.01)
                    if max_capacity != -1 and max_recive != -1:
                        # 活动医院容量未达无穷大
                        if max_recive > capacity_sum:
                            return genFailMessage(
                                f"[PID={project}] 活动医院 提前复活最大档位({max_recive}) > 医院容量总和({capacity_sum})")

                # 移城道具有配置
                if len(basic['move_city_reward']) <= 0:
                    return genFailMessage(
                        f"[PID={project}] 未在基础信息中配置移城道具")

                # 轮次数不超过十场
                if reward['groupBasic']['group_match_number'] + reward['ringBasic']['ring_match_number'] + reward['peakBasic']['use_peak_match'] > 10:
                    return genFailMessage(
                        f"[PID={project}] 小组赛场次({reward['groupBasic']['group_match_number']}) + 擂台赛场次({reward['ringBasic']['ring_match_number']}) + 巅峰擂台赛场次({reward['peakBasic']['use_peak_match']}) > 10")
                # 小组赛/擂台赛至少有一场
                if reward['groupBasic']['group_match_number'] + reward['ringBasic']['ring_match_number'] <= 0:
                    return genFailMessage(f"[PID={project}] 小组赛和擂台赛至少配置1场")
                # 巅峰擂台赛前至少有一场擂台赛
                if reward['peakBasic']['use_peak_match'] > 0 and reward['ringBasic']['ring_match_number'] <= 0:
                    return genFailMessage(f"[PID={project}] 开启巅峰擂台赛时至少需要有一场擂台赛")

        except Exception as e:
            logging.exception(e)
            print('\033[31m[ERROR] [check_before_public]', e, '\033[0m')
            return json.dumps({
                "status": "fail",
                "msg": "意外错误"
            })
        return json.dumps({
            "status": "success",
            "msg": "校验成功"
        })
    elif _action == 'get_score_building_conf':
        with open(STATIC_PATH + 'conquest_match_event_project/score_building.json', encoding='UTF-8') as f:
            data = json.load(f)
            return json.dumps(data)
    elif _action == 'update_score_building_conf':
        with open(STATIC_PATH + 'conquest_match_event_project/score_building.json', "w", encoding='UTF-8') as f:
            json.dump(params['data'], f)
    elif _action == 'get_test_control':
        with open(STATIC_PATH + 'conquest_match_event_project/test_control.json', encoding='UTF-8') as f:
            data = json.load(f)
            return json.dumps(data)
    elif _action == 'update_test_control':
        with open(STATIC_PATH + 'conquest_match_event_project/test_control.json', "w", encoding='UTF-8') as f:
            json.dump(params['data'], f)
    return jsonify(result_data)


@conquest_match_event_project_down_api.route('/conquest_match_event_project_down/<int:is_push>/<int:file_index>', methods=['GET', 'POST'])
def conquest_match_event_project_down(is_push, file_index):
    if file_index == 5:
        force_control = {}
        with open(STATIC_PATH + 'conquest_match_event_project/test_control.json', encoding='UTF-8') as f:
            data = json.load(f)
        for i in data:
            sid_list = ToSidList(str(i['sid']))
            for j in sid_list:
                force_control[j] = i['force']

        test_control = {
            'force_control': force_control
        }
        if is_push == 0:
            response = DownLoad('conquest_match_sid_event_test_control', test_control, 0)
            return response
        else:
            response = DownLoad('conquest_match_sid_event_test_control', test_control, 1)
            if response:
                return jsonify({"msg": "发布成功", "ret": 1})
            else:
                return False


    def get_reward_info(r):
        t = {"a": [r['type'], r['id'], r['num']]}
        return t

    def get_reward_list(a):
        tmp_reward = []
        for i in range(0, len(a)):
            for j in range(0, len(a[i]['reward'])):
                tmp_reward.append(get_reward_info(a[i]['reward'][j]))
        return tmp_reward

    def find_task(task_id, task_data):
        for task in task_data:
            if task['index'] == task_id:
                return task
        return {}

    def gen_rank_reward_list_add_token(_token_type, _token_id, r_list):
        _rank_reward_list = []
        for i in r_list:
            _reward = RewardToTMysqlNew(i['reward'])
            if i['token'] > 0:
                _reward = _reward + [{'a': [_token_type, _token_id, i['token']]}]
            _rank_reward_list.append({
                'from': i['from'],
                'to': i['to'],
                'reward': copy.deepcopy(_reward),
                'token': i['token']
            })
        return _rank_reward_list

    def gen_goal_reward_list_add_token(_g_id, _token_type, _token_id, r_list):
        _goal_reward = []
        for i in r_list:
            _g_id = _g_id + 1
            _reward = RewardToTMysqlNew(i['reward'])
            if i['token'] > 0:
                _reward = _reward + [{'a': [token_type, token_id, i['token']]}]
            _goal_reward.append({
                'from': 1,
                'to': i['to'],
                'reward': copy.deepcopy(_reward),
                'token': i['token'],
                'goal_id': _g_id
            })
        return {
            'global_goal_id': _g_id,
            'goal_reward_list': _goal_reward
        }

    token_type = 117
    token_id = 2800
    t2_type = 180
    t2_id = 1

    _conquest_match_sid_event_project = {}
    _conquest_match_user_event_project = {}
    _event_hosptal_project = {}
    _conquest_match_score_building_conf = {}


    query = ConquestMatchEventProject.query.order_by('project').all()

    for q in query:
        _project = str(q.project)
        basic = json.loads(q.basic)
        reward = json.loads(q.reward)
        task_desc = json.loads(q.task_desc)

        _battle_type = []
        _battle_type = _battle_type + [0] * reward['groupBasic']['group_match_number']
        _battle_type = _battle_type + [1] * reward['ringBasic']['ring_match_number']
        _battle_type = _battle_type + [2] * reward['peakBasic']['use_peak_match']

        _rank_size_arr = []
        if len(reward['serverPointBronze']) > 0:
            _sid_num = 0
            _init_league_score = []
            for i in reward['serverPointBronze']:
                current_num = i['to'] - i['from'] + 1
                _sid_num = _sid_num + current_num
                _init_league_score = _init_league_score + [i['score']] * current_num
            _rank_size_arr.append({
                'rank_index': 100,
                'sid_num': _sid_num,
                'group_num': reward['battle_num']['bronze'],
                'init_league_score': _init_league_score
            })
        if len(reward['serverPointSilver']) > 0:
            _sid_num = 0
            _init_league_score = []
            for i in reward['serverPointSilver']:
                current_num = i['to'] - i['from'] + 1
                _sid_num = _sid_num + current_num
                _init_league_score = _init_league_score + [i['score']] * current_num
            _rank_size_arr.append({
                'rank_index': 101,
                'sid_num': _sid_num,
                'group_num': reward['battle_num']['silver'],
                'init_league_score': _init_league_score
            })
        if len(reward['serverPointGold']) > 0:
            _sid_num = 0
            _init_league_score = []
            for i in reward['serverPointGold']:
                current_num = i['to'] - i['from'] + 1
                _sid_num = _sid_num + current_num
                _init_league_score = _init_league_score + [i['score']] * current_num
            _rank_size_arr.append({
                'rank_index': 102,
                'sid_num': _sid_num,
                'group_num': reward['battle_num']['gold'],
                'init_league_score': _init_league_score
            })

        _rank_reward = {}
        _goal_reward = {}
        _global_goal_id = 0
        # 0-服务器总榜
        _rank_reward_list = []
        for i in reward['globalServerRankReward']:
            _rank_reward_list.append({
                'from': i['from'],
                'to': i['to'],
                'reward': RewardToTMysqlNew(i['reward']),
                'token': 0
            })
        _rank_reward['0'] = {
            'rank_size': 200,
            'show_size': 200,
            'limit_score': 0,
            'rank_reward_list': copy.deepcopy(_rank_reward_list),
            'master_rank_reward': [],
            'top_ring_rank_reward': []
        }

        # 1-总个人积分榜
        _rank_reward_list = []
        for i in reward['globalPersonalRank']['reward']:
            _rank_reward_list.append({
                'from': i['from'],
                'to': i['to'],
                'reward': RewardToTMysqlNew(i['reward'])
            })
        _rank_reward['1'] = {
            'rank_size': 200,
            'show_size': reward['globalPersonalRank']['show_size'],
            'limit_score': reward['globalPersonalRank']['limit_score'],
            'rank_reward': copy.deepcopy(_rank_reward_list)
        }

        # 2-服务器积分榜
        _rank_reward_list = []
        for i in reward['subServer']['rankRewardGroup']:
            _reward = []
            if i['token'] > 0:
                _reward = _reward + [{'a': [t2_type, t2_id, i['token']]}]
            _rank_reward_list.append({
                'from': i['server_rank'],
                'to': i['server_rank'],
                'reward': _reward,
                'token': i['token']
            })
        _ring_win_reward_list = []
        for i in reward['subServer']['rankRewardRingWin']:
            _reward = []
            if i['token'] > 0:
                _reward = _reward + [{'a': [t2_type, t2_id, i['token']]}]
            _ring_win_reward_list.append({
                'from': i['server_rank'],
                'to': i['server_rank'],
                'reward': _reward,
                'token': i['token']
            })
        _ring_lose_reward_list = []
        for i in reward['subServer']['rankRewardRingLose']:
            _reward = []
            if i['token'] > 0:
                _reward = _reward + [{'a': [t2_type, t2_id, i['token']]}]
            _ring_lose_reward_list.append({
                'from': i['server_rank'],
                'to': i['server_rank'],
                'reward': _reward,
                'token': i['token']
            })
        _peak_win_reward_list = []
        for i in reward['subServer']['rankRewardPeakWin']:
            _reward = []
            if i['token'] > 0:
                _reward = _reward + [{'a': [t2_type, t2_id, i['token']]}]
            _peak_win_reward_list.append({
                'from': i['server_rank'],
                'to': i['server_rank'],
                'reward': _reward,
                'token': i['token']
            })
        _peak_lose_reward_list = []
        for i in reward['subServer']['rankRewardPeakLose']:
            _reward = []
            if i['token'] > 0:
                _reward = _reward + [{'a': [t2_type, t2_id, i['token']]}]
            _peak_lose_reward_list.append({
                'from': i['server_rank'],
                'to': i['server_rank'],
                'reward': _reward,
                'token': i['token']
            })
        _rank_reward['2'] = {
            'rank_size': 200,
            'show_size': 200,
            'limit_score': 0,
            'rank_reward_list': copy.deepcopy(_rank_reward_list),
            'master_rank_reward': [copy.deepcopy(_ring_win_reward_list), copy.deepcopy(_ring_lose_reward_list)],
            'top_ring_rank_reward': [copy.deepcopy(_peak_win_reward_list), copy.deepcopy(_peak_lose_reward_list)]
        }

        # 3-王城占领榜
        _group_rank_reward_list = gen_rank_reward_list_add_token(token_type, reward['token_id'], reward['empire']['groupRank'])
        _ring_rank_reward_list = gen_rank_reward_list_add_token(token_type, reward['token_id'], reward['empire']['ringRank'])
        _peak_rank_reward_list = gen_rank_reward_list_add_token(token_type, reward['token_id'], reward['empire']['peakRank'])
        temp = gen_goal_reward_list_add_token(_global_goal_id, token_type, reward['token_id'], reward['empire']['groupGoal'])
        _group_goal_reward_list = copy.deepcopy(temp['goal_reward_list'])
        _global_goal_id = temp['global_goal_id']
        temp = gen_goal_reward_list_add_token(_global_goal_id, token_type, reward['token_id'], reward['empire']['ringGoal'])
        _ring_goal_reward_list = copy.deepcopy(temp['goal_reward_list'])
        _global_goal_id = temp['global_goal_id']
        temp = gen_goal_reward_list_add_token(_global_goal_id, token_type, reward['token_id'], reward['empire']['peakGoal'])
        _peak_goal_reward_list = copy.deepcopy(temp['goal_reward_list'])
        _global_goal_id = temp['global_goal_id']


        _rank_reward['3'] = {
            'rank_size': 200,
            'show_size': reward['empire']['show_size'],
            'limit_score': reward['empire']['limit_score'],
            'team_rank_reward_list': _group_rank_reward_list,
            'ring_rank_reward_list': _ring_rank_reward_list,
            'top_rank_reward_list': _peak_rank_reward_list
        }

        _goal_reward['3'] = {
            'team_goal_reward': _group_goal_reward_list,
            'ring_goal_reward': _ring_goal_reward_list,
            'top_goal_reward': _peak_goal_reward_list
        }

        # 4-卫城占领榜
        _group_rank_reward_list = gen_rank_reward_list_add_token(token_type, reward['token_id'], reward['satellite']['groupRank'])
        _ring_rank_reward_list = gen_rank_reward_list_add_token(token_type, reward['token_id'], reward['satellite']['ringRank'])
        _peak_rank_reward_list = gen_rank_reward_list_add_token(token_type, reward['token_id'], reward['satellite']['peakRank'])
        temp = gen_goal_reward_list_add_token(_global_goal_id, token_type, reward['token_id'], reward['satellite']['groupGoal'])
        _group_goal_reward_list = copy.deepcopy(temp['goal_reward_list'])
        _global_goal_id = temp['global_goal_id']
        temp = gen_goal_reward_list_add_token(_global_goal_id, token_type, reward['token_id'], reward['satellite']['ringGoal'])
        _ring_goal_reward_list = copy.deepcopy(temp['goal_reward_list'])
        _global_goal_id = temp['global_goal_id']
        temp = gen_goal_reward_list_add_token(_global_goal_id, token_type, reward['token_id'], reward['satellite']['peakGoal'])
        _peak_goal_reward_list = copy.deepcopy(temp['goal_reward_list'])
        _global_goal_id = temp['global_goal_id']

        _rank_reward['4'] = {
            'rank_size': 200,
            'show_size': reward['satellite']['show_size'],
            'limit_score': reward['satellite']['limit_score'],
            'team_rank_reward_list': _group_rank_reward_list,
            'ring_rank_reward_list': _ring_rank_reward_list,
            'top_rank_reward_list': _peak_rank_reward_list
        }
        _goal_reward['4'] = {
            'team_goal_reward': _group_goal_reward_list,
            'ring_goal_reward': _ring_goal_reward_list,
            'top_goal_reward': _peak_goal_reward_list
        }

        # 5-骁勇榜
        _group_rank_reward_list = gen_rank_reward_list_add_token(token_type, reward['token_id'], reward['brave']['rank'])
        temp = gen_goal_reward_list_add_token(_global_goal_id, token_type, reward['token_id'], reward['brave']['goal'])
        _group_goal_reward_list = copy.deepcopy(temp['goal_reward_list'])
        _global_goal_id = temp['global_goal_id']

        _rank_reward['5'] = {
            'rank_size': 200,
            'show_size': reward['brave']['show_size'],
            'limit_score': reward['brave']['limit_score'],
            'rank_reward': _group_rank_reward_list
        }
        _goal_reward['5'] = {
            'goal_reward': _group_goal_reward_list
        }

        _legal_score_type = []
        _sid_legal_score_type = []
        _sid_task_desc = []
        _user_task_desc = []
        with open(STATIC_PATH + 'conquest_match_event_project/task_list.json', encoding='UTF-8') as f:
            task_list = json.load(f)
        temp_task_list = task_desc['server_task_list'] + task_desc['user_task_list']
        for i in temp_task_list:
            t = find_task(i['task_id'], task_list)
            task_obj = {
                'type': t['type'],
                'id_list': t['id_list'],
                'lv_list': t['lv_list'],
                'id_class': t['id_class'],
                'doc_id': i['doc_id'],
                'num_unit': t['num_unit'],
                'class': t['class'],
                'hide': t['hide'],
                'num': i['num'],
                'score': i['score'],
                'rank_type': t['rank_type']
            }
            if t['rank_type'] in [0, 2]:  # sid task
                _sid_task_desc.append(copy.deepcopy(task_obj))
                _sid_legal_score_type.append(t['type'])
            else:  # user task
                _legal_score_type.append(t['type'])
                _user_task_desc.append(copy.deepcopy(task_obj))

                if task_obj['type'] == 10001:
                    temp_task = copy.deepcopy(task_obj)
                    temp_task['hide'] = 1
                    temp_task['score'] = math.ceil(temp_task['score'] * task_desc['task_param_1'] * 0.01)
                    temp_task['type'] = 10002
                    if t['id_list'][0] == 71:
                        temp_task['doc_id'] = 7117
                        _legal_score_type.append(10002)
                        _user_task_desc.append(copy.deepcopy(temp_task))
                    if t['id_list'][0] == 72:
                        temp_task['doc_id'] = 7118
                        _legal_score_type.append(10002)
                        _user_task_desc.append(copy.deepcopy(temp_task))

        default_task_obj = {
            'type': 100004,
            'id_list': [-1],
            'lv_list': [-1],
            'id_class': 0,
            'doc_id': 0,
            'num_unit': 1,
            'class': 1,
            'hide': 1,
            'num': 1,
            'score': 1,
            'rank_type': 1
        }
        _user_task_desc.append(copy.deepcopy(default_task_obj))
        _legal_score_type.append(100004)
        _legal_score_type = list(set(_legal_score_type))
        _sid_legal_score_type = list(set(_sid_legal_score_type))

        _conquest_match_sid_event_project[str(_project)] = {
            'proxy_set': {
                'legal_score_type': _sid_legal_score_type
            },
            'doc_id': basic['doc_id'],
            'event_ui': basic['ui'],
            'battle_type': _battle_type,
            'rank_size': _rank_size_arr,
            'ring_num': reward['ringBasic']['ring_num'],
            'civilian_time_num': basic['civilian_time_num'],
            'score_type_list': _sid_task_desc,
            'rank_reward': {
                '0': _rank_reward['0'],
                '2': _rank_reward['2']
            },
            'remark': q.remark
        }

        buff_query = CommonBuff.query.order_by('id').all()
        buff_1 = []
        buff_2 = []
        for i in buff_query:
            if i.id == basic['buff1_id']:
                buffs = json.loads(i.buff)
                for j in buffs:
                    buff_1.append([j['a'][0], j['a'][1]])
            if i.id == basic['buff2_id']:
                buffs = json.loads(i.buff)
                for j in buffs:
                    buff_2.append([j['a'][0], j['a'][1]])


        _conquest_match_user_event_project[str(_project)] = {
            'event_ui': basic['ui'],
            'doc_id': basic['doc_id'],
            'proxy_set': {
                'legal_score_type': _legal_score_type
            },
            'exchange_shop_type': basic['exchange_shop_type'],
            'battle_type': _battle_type,
            'civilian_time_num': basic['civilian_time_num'],
            'score_building_gems': basic['score_building_gems'],
            'event_hospital_open': reward['hospital']['switch'],
            'multi_calendar_conf': {
                '0': {
                    'event_type': 125,
                    'event_ui': basic['ui'],
                    'order': 1,
                    'jump': 1,
                    'localization': {
                        'title': basic['doc_id'],
                        'info': basic['doc_id']
                    },
                    'reward': RewardToTMysqlNew(basic['reward_show']),
                    'show_type': 0
                },
                '1': {
                    'event_type': 125,
                    'event_ui': basic['ui'] + 1,
                    'order': 1,
                    'jump': 1,
                    'localization': {
                        'title': basic['doc_id'] + 1,
                        'info': basic['doc_id'] + 1
                    },
                    'reward': RewardToTMysqlNew(reward['groupBasic']['group_show_reward']),
                    'show_type': 0
                },
                '2': {
                    'event_type': 125,
                    'event_ui': basic['ui'] + 2,
                    'order': 1,
                    'jump': 1,
                    'localization': {
                        'title': basic['doc_id'] + 2,
                        'info': basic['doc_id'] + 2
                    },
                    'reward': RewardToTMysqlNew(reward['ringBasic']['ring_show_reward']),
                    'show_type': 0
                },
                '3': {
                    'event_type': 125,
                    'event_ui': basic['ui'] + 3,
                    'order': 1,
                    'jump': 1,
                    'localization': {
                        'title': basic['doc_id'] + 3,
                        'info': basic['doc_id'] + 3
                    },
                    'reward': RewardToTMysqlNew(reward['peakBasic']['peak_show_reward']),
                    'show_type': 0
                }
            },
            'score_type_list': _user_task_desc,
            'forecast_reward': RewardToTMysqlNew(basic['reward_show']),
            'goal_reward': {
                '3': _goal_reward['3'],
                '4': _goal_reward['4'],
                '5': _goal_reward['5']
            },
            'rank_reward': {
                '1': _rank_reward['1'],
                '3': _rank_reward['3'],
                '4': _rank_reward['4'],
                '5': _rank_reward['5']
            },
            'buff_1': buff_1,
            'buff_2': buff_2,
            'x': basic['buff2_x'],
            'y': basic['buff2_y'],
            'remark': q.remark,
            'move_city': {
                'reward': [basic['move_city_reward'][0]['type'], basic['move_city_reward'][0]['id'], basic['move_city_reward'][0]['num']]
            }
        }

        _hospital = {}
        _revive = {}
        for i in reward['hospital']['capacity']:
            _hospital[i['capacity_to']] = i['percent'] * 100
        for i in reward['hospital']['revive']:
            _revive[i['to']] = RewardToTMysqlNew(i['reward'])

        _event_hosptal_project[str(int(_project) + 20000)] = {
            'switch': reward['hospital']['switch'],
            'basic': {
                'event_ui': 1
            },
            'localization': {
                'title': 31,
                'info': 31,
                'content': 31
            },
            'hosptal': _hospital,
            'revive_switch': reward['hospital']['revive_switch'],
            'troop_num_unit': reward['hospital']['troop_num_unit'],
            'revive': _revive
        }

    with open(STATIC_PATH + 'conquest_match_event_project/score_building.json', encoding='UTF-8') as f:
        score_building_data = json.load(f)

    for i in score_building_data:
        for j in range(i['from'], i['to'] + 1):
            _conquest_match_score_building_conf[str(j)] = {
                'x': i['x'],
                'y': i['y'],
                'z': i['z'],
                'num': i['num']
            }



    if is_push == 0:
        if file_index == 1:
            response = DownLoad('conquest_match_sid_event_project', _conquest_match_sid_event_project, 0)
        if file_index == 2:
            response = DownLoad('conquest_match_user_event_project', _conquest_match_user_event_project, 0)
        if file_index == 3:
            response = DownLoad('event_hosptal_project.conquest', _event_hosptal_project, 0)
        if file_index == 4:
            response = DownLoad('conquest_match_score_building_conf', _conquest_match_score_building_conf, 0)
    if is_push == 1:
        r1 = DownLoad('conquest_match_sid_event_project', _conquest_match_sid_event_project, 1)
        r2 = DownLoad('conquest_match_user_event_project', _conquest_match_user_event_project, 1)
        r3 = DownLoad('event_hosptal_project.conquest', _event_hosptal_project, 1)
        r4 = DownLoad('conquest_match_score_building_conf', _conquest_match_score_building_conf, 1)
        if r1 and r2 and r3 and r4:
            return jsonify({"msg": "发布成功", "ret": 1})
        else:
            return False

    return response


@conquest_match_event_project_optimization_update_api.route('/conquest_match_event_project_optimization_update', methods=['GET', 'POST'])
def conquest_match_event_project_optimization_update():
    project_data = ConquestMatchEventProject.query.all()
    for i in project_data:
        reward = json.loads(i.reward)
        if 'token_id' not in reward:
            reward['token_id'] = 2800
        #reward['token_id'] = 2800
        if 'troop_num_unit' not in reward['hospital']:
            reward['hospital']['troop_num_unit'] = 1
        i.reward = json.dumps(reward)

        task_desc = json.loads(i.task_desc)
        if 'task_list' in task_desc:
            task_desc['server_task_list'] = []
            task_desc['user_task_list'] = []
            for j in task_desc['task_list']:
                if j['rank_type'] in [0, 2]:
                    task_desc['server_task_list'].append(copy.deepcopy(j))
                else:
                    task_desc['user_task_list'].append(copy.deepcopy(j))
            del task_desc['task_list']
        i.task_desc = json.dumps(task_desc)

        basic = json.loads(i.basic)
        if 'score_building_gems' not in basic:
            basic['score_building_gems'] = 0
        if 'move_city_reward' not in basic:
            basic['move_city_reward'] = [{"name": "Realm of Conquest Teleport-5986", "num": 2, "type": 0, "price": 1500, "id": 5986}]
        i.basic = json.dumps(basic)
    db.session.commit()
    return jsonify({'msg': 'finished'})


@conquest_match_event_project_group_num_update_api.route('/conquest_match_event_project_group_num_update', methods=['GET', 'POST'])
def conquest_match_event_project_group_num_update():
    project_data = ConquestMatchEventProject.query.all()
    for i in project_data:
        reward = json.loads(i.reward)
        if 'group_num' in reward['groupBasic']:
            reward['battle_num'] = {
                'bronze': reward['groupBasic']['group_num'],
                'silver': reward['groupBasic']['group_num'],
                'gold': reward['groupBasic']['group_num']
            }
            del reward['groupBasic']['group_num']
        i.reward = json.dumps(reward)
    db.session.commit()
    return jsonify({'msg': 'finished'})
